package com.example.contentproviders;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class BooksProvider extends ContentProvider {

    static final  String PROVIDER_NAME = "com.example.contentproviders.Books";

    static final Uri CONTACT_URI = Uri.parse("content://" + PROVIDER_NAME + "/books");

    static final String _ID = "_id";
    static final String TITLE = "title";
    static final String ISBN = "isbn";

    static final int BOOKS = 1;
    static final int BOOK_ID = 2;

    private static final UriMatcher uriMather;

    static {
        uriMather = new UriMatcher(UriMatcher.NO_MATCH);
        uriMather.addURI(PROVIDER_NAME, "books", BOOKS);
        uriMather.addURI(PROVIDER_NAME, "books/#", BOOK_ID);
    }

    SQLiteDatabase booksDB;
    static final String DATABASE_NAME = "Books";
    static final String DATABASE_TABLE = "titles";
    static final int DATABASE_VERSION = 1;
    static final String DATABASE_CREATE = "create table "+ DATABASE_TABLE+" (_id integer primary key autoincrement, title text not null, isbn text not null);";

    private static class DatabaseHelper extends SQLiteOpenHelper
    {

        DatabaseHelper(Context context){
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try{
                db.execSQL(DATABASE_CREATE);
            } catch (SQLException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w("ContentProviderDatabase", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data");
            db.execSQL("drop table if exists "+ DATABASE_TABLE);
            onCreate(db);
        }
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        int count = 0;
        switch (uriMather.match(uri)){
            case BOOKS:
                count = booksDB.delete(DATABASE_TABLE, selection, selectionArgs);
                break;
            case BOOK_ID:
                String id = uri.getPathSegments().get(1);
                count = booksDB.delete(DATABASE_TABLE, _ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" :""), selectionArgs);
                break;
            default: throw new IllegalArgumentException("Unknown URI" + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMather.match(uri)){
            case BOOKS:
                return "vnd.android.cursor.dir/vnd.example.books ";
            case BOOK_ID:
               return "vnd.android.cursor.item/vnd.example.books ";
            default: throw new IllegalArgumentException("Unsupported URI" + uri);
        }
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        long rowID = booksDB.insert(DATABASE_TABLE, "", values);
        if(rowID > 0){
            Uri _uri = ContentUris.withAppendedId(CONTACT_URI, rowID);
            getContext().getContentResolver().notifyChange(_uri, null);
            return _uri;
        }
        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        DatabaseHelper dbHelper = new DatabaseHelper(context);
        booksDB = dbHelper.getWritableDatabase();
        return (booksDB == null) ? false : true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
        sqlBuilder.setTables(DATABASE_TABLE);
        if(uriMather.match(uri)  == BOOK_ID){
            sqlBuilder.appendWhere(_ID + " = " + uri.getPathSegments().get(1));
        }
        if(sortOrder == null || sortOrder == ""){
            sortOrder = TITLE;
        }

        Cursor cursor = sqlBuilder.query(booksDB, projection, selection, selectionArgs, null, null, sortOrder);

        cursor.setNotificationUri(getContext().getContentResolver(), uri);

        return cursor;
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        int count = 0;
        switch (uriMather.match(uri)){
            case BOOKS:
                count = booksDB.update(DATABASE_TABLE, values, selection, selectionArgs);
                break;
            case BOOK_ID:
                String id = uri.getPathSegments().get(1);
                count = booksDB.update(DATABASE_TABLE, values, _ID + " = " + id + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" :""), selectionArgs);
                break;
            default: throw new IllegalArgumentException("Unknown URI" + uri);
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
}
